@using MudBlazor
@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Components
@using Nethereum.Wallet.UI.Components.Core.Localization
@using static Nethereum.Wallet.UI.Components.Dialogs.Localization.PasswordConfirmationDialogLocalizer

<MudDialog>
    <DialogContent>
        <MudForm @ref="form" @bind-IsValid="IsFormValid">
            <MudStack Spacing="4">
                <MudStack AlignItems="AlignItems.Center" Spacing="3">
                    <MudStack AlignItems="AlignItems.Center" Spacing="1">
                        <MudText Typo="Typo.h6">@Title</MudText>
                        <MudText Typo="Typo.body2" Color="Color.Secondary" Align="Align.Center">
                            @Message
                        </MudText>
                    </MudStack>
                </MudStack>

                <MudTextField @bind-Value="@Password"
                              Label="@Localizer.GetString(Keys.WalletPasswordLabel)"
                              Variant="Variant.Outlined"
                              InputType="@(showPassword ? InputType.Text : InputType.Password)"
                              Required="true"
                              RequiredError="@Localizer.GetString(Keys.PasswordRequiredError)"
                              Immediate="true"
                              Adornment="Adornment.End"
                              AdornmentIcon="@(showPassword ? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
                              OnAdornmentClick="TogglePasswordVisibility"
                              AdornmentAriaLabel="@Localizer.GetString(Keys.TogglePasswordVisibilityLabel)"
                              HelperText="@Localizer.GetString(Keys.PasswordHelperText)"
                              @onkeypress="@(async (e) => { if (e.Key == "Enter" && CanConfirm) await ConfirmAction(); })" />

                @if (!string.IsNullOrEmpty(ErrorMessage))
                {
                    <MudAlert Severity="Severity.Error">
                        @ErrorMessage
                    </MudAlert>
                }
            </MudStack>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel" Variant="Variant.Text" Color="Color.Default">
            @Localizer.GetString(Keys.CancelButtonText)
        </MudButton>
        <MudButton Color="Color.Primary" 
                   Variant="Variant.Filled" 
                   OnClick="ConfirmAction"
                   Disabled="@(!CanConfirm)">
            @ConfirmButtonText
        </MudButton>
    </DialogActions>
</MudDialog>

@inject IComponentLocalizer<object> Localizer

@code {
    [CascadingParameter] 
    IMudDialogInstance MudDialog { get; set; } = null!;

    [Parameter] public string Title { get; set; } = "";
    [Parameter] public string Message { get; set; } = "";
    [Parameter] public string ConfirmButtonText { get; set; } = "";
    [Parameter] public Func<string, Task<(bool Success, string? ErrorMessage)>>? OnPasswordValidation { get; set; }

    private MudForm form = null!;
    private string Password = "";
    private string ErrorMessage = "";
    private bool showPassword = false;
    private bool IsFormValid = false;
    private bool isValidating = false;

    private bool CanConfirm => IsFormValid && !string.IsNullOrWhiteSpace(Password) && !isValidating;

    private void TogglePasswordVisibility()
    {
        showPassword = !showPassword;
    }

    private async Task ConfirmAction()
    {
        if (!CanConfirm)
            return;

        isValidating = true;
        ErrorMessage = "";
        StateHasChanged();

        try
        {
            if (OnPasswordValidation != null)
            {
                var result = await OnPasswordValidation(Password);
                if (!result.Success)
                {
                    ErrorMessage = result.ErrorMessage ?? Localizer.GetString(Keys.InvalidPasswordError);
                    StateHasChanged();
                    return;
                }
            }

            // Password is valid, close dialog with success
            MudDialog.Close(DialogResult.Ok(Password));
        }
        catch (Exception ex)
        {
            ErrorMessage = Localizer.GetString(Keys.ValidationError, ex.Message);
            StateHasChanged();
        }
        finally
        {
            isValidating = false;
            StateHasChanged();
        }
    }

    private void Cancel()
    {
        MudDialog.Cancel();
    }

    protected override void OnInitialized()
    {
        // Clear any previous state
        Password = "";
        ErrorMessage = "";
        showPassword = false;
        
        // Set default localized values if not provided
        if (string.IsNullOrEmpty(Title))
            Title = Localizer.GetString(Keys.DefaultTitle);
        if (string.IsNullOrEmpty(Message))
            Message = Localizer.GetString(Keys.DefaultMessage);
        if (string.IsNullOrEmpty(ConfirmButtonText))
            ConfirmButtonText = Localizer.GetString(Keys.ConfirmButtonText);
    }
}